<template>
	<view class="edit-container">
		<!-- 状态栏占位 -->
		<view class="status-bar" :style="{height: statusBarHeight + 'px'}"></view>
		
		<!-- 简化的导航栏 -->
		<view class="navbar">
			<view class="navbar-left" @click="goBack">
				<text class="back-icon">‹</text>
				<text class="back-text">返回</text>
			</view>
			<text class="navbar-title">{{ isEdit ? '编辑备忘录' : '新建备忘录' }}</text>
			<view class="navbar-right">
				<!-- 空白占位，保持标题居中 -->
			</view>
		</view>
		
		<!-- 可滚动的编辑区域 -->
		<scroll-view 
			class="edit-content" 
			:scroll-y="true"
			:scroll-top="scrollTop"
			:scroll-with-animation="true"
			:enable-back-to-top="false"
		>
			<!-- 标题输入 -->
			<view class="input-section">
				<input 
					class="title-input" 
					v-model="memoData.title"
					placeholder="请输入标题..."
					:maxlength="50"
					@input="onTitleInput"
				/>
				<text class="char-count">{{ titleLength }}/50</text>
			</view>
			
			<!-- 内容输入区域 -->
			<view class="textarea-section" id="textarea-container">
				<textarea 
					class="content-textarea"
					v-model="memoData.content"
					placeholder="在这里记录你的想法..."
					:maxlength="2000"
					:auto-height="true"
					:cursor-spacing="120"
					:adjust-position="true"
					:show-confirm-bar="false"
					@input="onContentInput"
					@focus="onContentFocus"
					@blur="onContentBlur"
					@linechange="onLineChange"
				/>
				<text class="char-count">{{ contentLength }}/2000</text>
			</view>
			
			<!-- 底部占位，确保内容不被键盘遮挡 -->
			<view class="bottom-spacer" :style="{height: keyboardHeight + 'px'}"></view>
		</scroll-view>
		
		<!-- 底部操作区 -->
		<view class="bottom-container">
			<!-- 工具栏 -->
			<view class="bottom-toolbar">
				<view class="tool-item" @click="insertCurrentTime">
					<text class="tool-icon">🕐</text>
					<text class="tool-text">时间</text>
				</view>
				<view class="tool-item" @click="showCategoryPicker">
					<text class="tool-icon">📂</text>
					<text class="tool-text">分类</text>
				</view>
				<view class="tool-item" @click="toggleImportant">
					<text class="tool-icon">{{ memoData.important ? '⭐' : '☆' }}</text>
					<text class="tool-text">重要</text>
				</view>
			</view>
			
			<!-- 保存按钮 -->
			<view class="save-button-container">
				<view class="save-button" @click="saveMemo">
					<view class="save-icon">
						<text class="save-icon-text">✓</text>
					</view>
					<text class="save-button-text">保存备忘录</text>
				</view>
			</view>
		</view>
		
		<!-- 分类选择器 -->
		<view class="category-modal" v-if="showCategory" @click="hideCategoryPicker">
			<view class="category-content" @click.stop>
				<view class="category-header">
					<text class="category-title">选择分类</text>
					<view class="close-btn" @click="hideCategoryPicker">
						<text class="close-icon">×</text>
					</view>
				</view>
				<view class="category-list">
					<view 
						class="category-item"
						v-for="(item, index) in categories"
						:key="index"
						:class="{ active: memoData.category === item.value }"
						@click="selectCategory(item)"
					>
						<text class="category-emoji">{{ item.emoji }}</text>
						<text class="category-name">{{ item.name }}</text>
						<text class="check-icon" v-if="memoData.category === item.value">✓</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 保存确认弹窗 -->
		<view class="save-modal" v-if="showSaveModal" @click="hideSaveModal">
			<view class="save-content" @click.stop>
				<view class="save-header">
					<text class="save-title">保存备忘录</text>
				</view>
				<view class="save-body">
					<text class="save-text">确定要保存这条备忘录吗？</text>
				</view>
				<view class="save-footer">
					<view class="save-btn cancel-btn" @click="hideSaveModal">
						<text class="btn-text">取消</text>
					</view>
					<view class="save-btn confirm-btn" @click="confirmSave">
						<text class="btn-text">保存</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import localStorage from '@/utils/storage.js'

export default {
	data() {
		return {
			isEdit: false,
			memoId: '',
			memoData: {
				title: '',
				content: '',
				category: 'general',
				important: false
			},
			showCategory: false,
			showSaveModal: false,
			statusBarHeight: 0,
			keyboardHeight: 0,
			scrollTop: 0,
			isKeyboardVisible: false,
			categories: [
				{ name: '普通', value: 'general', emoji: '📝' },
				{ name: '工作', value: 'work', emoji: '💼' },
				{ name: '生活', value: 'life', emoji: '🏠' },
				{ name: '学习', value: 'study', emoji: '📚' },
				{ name: '旅行', value: 'travel', emoji: '✈️' },
				{ name: '购物', value: 'shopping', emoji: '🛒' },
				{ name: '健康', value: 'health', emoji: '💪' },
				{ name: '娱乐', value: 'entertainment', emoji: '🎮' },
				{ name: '管理', value: 'admin', emoji: '🔧' }
			]
		}
	},
	
	computed: {
		titleLength() {
			return this.memoData.title.length;
		},
		contentLength() {
			return this.memoData.content.length;
		}
	},
	
	onLoad(options) {
		// 获取状态栏高度
		this.getStatusBarHeight();
		
		// 监听键盘高度变化
		uni.onKeyboardHeightChange(this.onKeyboardHeightChange);
		
		if (options.id) {
			this.isEdit = true;
			this.memoId = options.id;
			this.loadMemoData();
		}
	},
	
	onUnload() {
		// 移除键盘监听
		uni.offKeyboardHeightChange(this.onKeyboardHeightChange);
	},
	
	methods: {
		// 获取适配的状态栏高度
		getStatusBarHeight() {
			const systemInfo = uni.getSystemInfoSync();
			let statusBarHeight = systemInfo.statusBarHeight || 0;
			
			// #ifdef MP-WEIXIN
			if (statusBarHeight === 0) {
				statusBarHeight = 25;
			}
			statusBarHeight = Math.max(statusBarHeight, 22);
			// #endif
			
			// #ifdef MP-ALIPAY
			if (statusBarHeight === 0) {
				statusBarHeight = 20;
			}
			// #endif
			
			// #ifdef H5
			statusBarHeight = 0;
			// #endif
			
			this.statusBarHeight = statusBarHeight;
		},
		
		loadMemoData() {
			// 使用本地存储加载备忘录数据
			const result = localStorage.getMemoDetail(this.memoId);
			if (result.success) {
				this.memoData = {
					title: result.data.title || '',
					content: result.data.content || '',
					category: result.data.category || 'general',
					important: result.data.important || false
				};
			} else {
				uni.showToast({
					title: '备忘录不存在',
					icon: 'none'
				});
				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
			}
		},
		
		onTitleInput(e) {
			this.memoData.title = e.detail.value;
		},
		
		onContentInput(e) {
			this.memoData.content = e.detail.value;
			
			// 在输入时自动滚动确保当前输入位置可见
			if (this.isKeyboardVisible) {
				// 延迟一点点时间，确保内容已经渲染
				this.$nextTick(() => {
					setTimeout(() => {
						this.scrollToBottom();
					}, 50);
				});
			}
		},
		
		onContentFocus() {
			console.log('内容输入框获得焦点');
			this.isKeyboardVisible = true;
			// 延迟滚动到合适位置
			setTimeout(() => {
				this.scrollToTextarea();
			}, 300);
		},
		
		onContentBlur() {
			console.log('内容输入框失去焦点');
			this.isKeyboardVisible = false;
		},
		
		onLineChange(e) {
			// 当行数改变时（通常是输入了换行符），自动滚动
			if (this.isKeyboardVisible) {
				this.$nextTick(() => {
					this.scrollToBottom();
				});
			}
		},
		
		onKeyboardHeightChange(res) {
			console.log('键盘高度变化:', res.height);
			this.keyboardHeight = res.height;
			
			if (res.height > 0) {
				// 键盘弹出
				this.isKeyboardVisible = true;
				setTimeout(() => {
					this.scrollToTextarea();
				}, 100);
			} else {
				// 键盘收起
				this.isKeyboardVisible = false;
			}
		},
		
		scrollToTextarea() {
			// 滚动到textarea区域，确保输入内容可见
			const query = uni.createSelectorQuery().in(this);
			query.select('#textarea-container').boundingClientRect((rect) => {
				if (rect) {
					// 计算滚动位置：textarea顶部位置 - 留一些空间给键盘
					const targetScrollTop = Math.max(0, rect.top - 100);
					this.scrollTop = targetScrollTop;
				}
			}).exec();
		},
		
		scrollToBottom() {
			// 当内容增加时，滚动到底部
			if (this.isKeyboardVisible) {
				this.$nextTick(() => {
					const query = uni.createSelectorQuery().in(this);
					query.select('.textarea-section').boundingClientRect((rect) => {
						if (rect) {
							// 滚动到底部，但留出键盘空间
							const scrollTo = rect.height + rect.top - 200;
							this.scrollTop = Math.max(0, scrollTo);
						}
					}).exec();
				});
			}
		},
		
		insertCurrentTime() {
			const now = new Date();
			const timeStr = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
			this.memoData.content += `\n\n⏰ ${timeStr}\n`;
		},
		
		showCategoryPicker() {
			this.showCategory = true;
		},
		
		hideCategoryPicker() {
			this.showCategory = false;
		},
		
		selectCategory(item) {
			this.memoData.category = item.value;
			this.hideCategoryPicker();
		},
		
		toggleImportant() {
			this.memoData.important = !this.memoData.important;
		},
		
		goBack() {
			if (this.hasUnsavedChanges()) {
				uni.showModal({
					title: '确认离开',
					content: '有未保存的内容，确定要离开吗？',
					success: (res) => {
						if (res.confirm) {
							uni.navigateBack();
						}
					}
				});
			} else {
				uni.navigateBack();
			}
		},
		
		hasUnsavedChanges() {
			return this.memoData.title.trim() || this.memoData.content.trim();
		},
		
		saveMemo() {
			if (!this.memoData.title.trim() && !this.memoData.content.trim()) {
				uni.showToast({
					title: '标题和内容不能都为空',
					icon: 'none'
				});
				return;
			}
			
			this.showSaveModal = true;
		},
		
		hideSaveModal() {
			this.showSaveModal = false;
		},
		
		confirmSave() {
			let result;
			
			if (this.isEdit) {
				// 更新备忘录
				result = localStorage.updateMemo(this.memoId, this.memoData);
			} else {
				// 创建新备忘录
				result = localStorage.createMemo(this.memoData);
			}
			
			if (result.success) {
				uni.showToast({
					title: result.message,
					icon: 'success'
				});
				
				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
			} else {
				uni.showToast({
					title: result.message || '保存失败',
					icon: 'none'
				});
			}
			
			this.hideSaveModal();
		}
	}
}
</script>

<style lang="scss" scoped>
.edit-container {
	width: 100%;
	height: 100vh;
	background: #f8f9fa;
	display: flex;
	flex-direction: column;
}

.status-bar {
	background: #6c5ce7;
}

.navbar {
	background: linear-gradient(135deg, #6c5ce7 0%, #a29bfe 100%);
	padding: 20rpx 30rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.navbar-left {
	display: flex;
	align-items: center;
}

.back-icon {
	font-size: 32rpx;
	color: white;
	font-weight: bold;
	margin-right: 8rpx;
}

.back-text {
	font-size: 28rpx;
	color: white;
}

.navbar-title {
	font-size: 32rpx;
	font-weight: bold;
	color: white;
}

.navbar-right {
	width: 80rpx;
	height: 60rpx;
}

.edit-content {
	flex: 1;
	padding: 20rpx;
}

.input-section {
	background: white;
	border-radius: 15rpx;
	padding: 25rpx 30rpx;
	margin-bottom: 20rpx;
	position: relative;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.title-input {
	width: 100%;
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	background: transparent;
	border: none;
	outline: none;
	padding-right: 80rpx;
}

.textarea-section {
	background: white;
	border-radius: 15rpx;
	padding: 30rpx;
	position: relative;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
	margin-bottom: 20rpx;
	min-height: 400rpx;
}

.content-textarea {
	width: 100%;
	font-size: 30rpx;
	color: #333;
	line-height: 1.8;
	background: transparent;
	border: none;
	outline: none;
	resize: none;
	word-wrap: break-word;
	min-height: 350rpx;
}

.char-count {
	position: absolute;
	bottom: 20rpx;
	right: 30rpx;
	font-size: 24rpx;
	color: #999;
	z-index: 1;
}

.bottom-spacer {
	width: 100%;
	transition: height 0.3s ease;
}

.bottom-container {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background: rgba(255, 255, 255, 0.95);
	backdrop-filter: blur(10px);
	border-top: 1rpx solid rgba(0, 0, 0, 0.08);
	padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
	z-index: 100;
}

.bottom-toolbar {
	display: flex;
	justify-content: space-around;
	padding: 15rpx 0 10rpx;
	border-bottom: 1rpx solid rgba(0, 0, 0, 0.05);
}

.tool-item {
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 8rpx 16rpx;
	border-radius: 12rpx;
	transition: all 0.3s ease;
	min-width: 70rpx;
}

.tool-item:active {
	background: rgba(108, 92, 231, 0.1);
	transform: scale(0.95);
}

.tool-icon {
	font-size: 24rpx;
	margin-bottom: 4rpx;
}

.tool-text {
	font-size: 18rpx;
	color: #666;
}

.save-button-container {
	padding: 15rpx 20rpx;
}

.save-button {
	width: 100%;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	border-radius: 20rpx;
	padding: 20rpx 0;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 8rpx 20rpx rgba(102, 126, 234, 0.3);
	transition: all 0.3s ease;
	position: relative;
	overflow: hidden;
}

.save-button:active {
	transform: scale(0.98);
	box-shadow: 0 4rpx 15rpx rgba(102, 126, 234, 0.2);
}

.save-button::before {
	content: '';
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: linear-gradient(135deg, transparent 0%, rgba(255, 255, 255, 0.1) 50%, transparent 100%);
	opacity: 0;
	transition: opacity 0.3s ease;
}

.save-button:active::before {
	opacity: 1;
}

.save-icon {
	width: 48rpx;
	height: 48rpx;
	background: rgba(255, 255, 255, 0.2);
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-right: 15rpx;
}

.save-icon-text {
	font-size: 24rpx;
	color: white;
	font-weight: bold;
}

.save-button-text {
	font-size: 28rpx;
	color: white;
	font-weight: 600;
}

.category-modal {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background: rgba(0, 0, 0, 0.5);
	z-index: 999;
	display: flex;
	align-items: flex-end;
}

.category-content {
	width: 100%;
	background: white;
	border-radius: 30rpx 30rpx 0 0;
	max-height: 80vh;
	animation: slideUp 0.3s ease-out;
}

@keyframes slideUp {
	from {
		transform: translateY(100%);
	}
	to {
		transform: translateY(0);
	}
}

.category-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 40rpx;
	border-bottom: 1rpx solid #f0f0f0;
}

.category-title {
	font-size: 36rpx;
	font-weight: bold;
	color: #333;
}

.close-btn {
	width: 60rpx;
	height: 60rpx;
	border-radius: 30rpx;
	background: #f5f5f5;
	display: flex;
	align-items: center;
	justify-content: center;
}

.close-icon {
	font-size: 32rpx;
	color: #666;
}

.category-list {
	max-height: 600rpx;
	overflow-y: scroll;
}

.category-item {
	display: flex;
	align-items: center;
	padding: 30rpx 40rpx;
	border-bottom: 1rpx solid #f8f8f8;
	transition: all 0.3s ease;
}

.category-item:active {
	background: #f8f8f8;
}

.category-item.active {
	background: rgba(166, 192, 254, 0.1);
}

.category-emoji {
	font-size: 32rpx;
	margin-right: 20rpx;
}

.category-name {
	flex: 1;
	font-size: 30rpx;
	color: #333;
}

.check-icon {
	font-size: 32rpx;
	color: #a6c0fe;
	font-weight: bold;
}

.save-modal {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background: rgba(0, 0, 0, 0.5);
	z-index: 999;
	display: flex;
	align-items: center;
	justify-content: center;
}

.save-content {
	background: white;
	border-radius: 20rpx;
	margin: 0 60rpx;
	width: calc(100% - 120rpx);
	max-width: 600rpx;
	overflow: hidden;
}

.save-header {
	padding: 40rpx;
	text-align: center;
	border-bottom: 1rpx solid #f0f0f0;
}

.save-title {
	font-size: 36rpx;
	font-weight: bold;
	color: #333;
}

.save-body {
	padding: 40rpx;
	text-align: center;
}

.save-text {
	font-size: 30rpx;
	color: #666;
	line-height: 1.5;
}

.save-footer {
	display: flex;
	border-top: 1rpx solid #f0f0f0;
}

.save-btn {
	flex: 1;
	padding: 30rpx 0;
	text-align: center;
	transition: all 0.3s ease;
}

.save-btn:active {
	background: #f5f5f5;
}

.cancel-btn {
	border-right: 1rpx solid #f0f0f0;
}

.cancel-btn:active {
	background: #f8f8f8;
}

.confirm-btn:active {
	background: rgba(166, 192, 254, 0.1);
}

.btn-text {
	font-size: 32rpx;
}

.cancel-btn .btn-text {
	color: #666;
}

.confirm-btn .btn-text {
	color: #a6c0fe;
	font-weight: 600;
}

/* 微信小程序适配 */
/* #ifdef MP-WEIXIN */
.bottom-container {
	padding-bottom: 30rpx;
}

.save-button-container {
	padding: 12rpx 20rpx;
}

.save-button {
	padding: 18rpx 0;
}

.save-icon {
	width: 40rpx;
	height: 40rpx;
	margin-right: 12rpx;
}

.save-icon-text {
	font-size: 20rpx;
}

.save-button-text {
	font-size: 26rpx;
}

.tool-item {
	padding: 6rpx 12rpx;
}

.tool-icon {
	font-size: 22rpx;
}

.tool-text {
	font-size: 16rpx;
}
/* #endif */
</style> 